// 16.最接近的三数之和
package Leetcode_Second_Brush;

import java.util.Arrays;

public class Solution016 {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);

        int result = nums[0] + nums[1] + nums[2];

        for (int first = 0; first < nums.length; first++) {
            if (first > 0 && nums[first] == nums[first - 1])
                continue;
            int second = first + 1;
            int third = nums.length - 1;
            while (second < third) {
                if (nums[second] + nums[third] == target - nums[first])
                    return target;
                else {
                    int value = nums[first] + nums[second] + nums[third];
                    if (Math.abs(target - result) > Math.abs(target - value))
                        result = value;
                    if (nums[second] + nums[third] > target - nums[first]) {
                        third--;
                    } else {
                        second++;
                    }
                }
            }
        }

        return result;
    }
}
